<template>
<div class="overview">
  <div class="top">
    <p class="pa-top">{{getCookie('sToken') === ''? '您未登录': `${getCookie('username')}`}} ，当前在：</p>
    <dl class="pa-title-wrap mgl-1rem">
      <dd :class="{'pa-title-item':true, 'on': selectSys == 0}" @click="selectSys=0">广场上</dd>
      <dd v-show="sToken !== ''" :class="{'pa-title-item':true, 'on': selectSys == 1}" @click="selectSys=1">个人记事</dd>
    </dl>
    <span id="send" @click="sendFrame='block', isLogin = false, isRegist = false"></span>
    
    <p class="pa-top" style="right: 2rem;text-align: right;">
      <span class="pa-link" @click="isLogin = true, isRegist = false, sendFrame = 'none'">登录 </span>/<span class="pa-link" @click="isRegist = true, isLogin = false, sendFrame = 'none'"> 注册</span>
    </p>
    <div>
      <div class="moa-search">
        <input class="search moa-input" type="text" placeholder="搜索：" name="searchText" v-model="searchText"/>
      </div>
    </div>
  </div>
  <div id="main">
    <dl class="paper a1" v-for="(item,index) in filterData(arr)" :key="item.id" v-drag="item" :jsId="item.id">
      <dt class="title">
        <p class="mg-0-auto text-a-r">
          <span class="num">{{item.num | num}}</span>
        </p>
      </dt>
      <dd class="content">
        <div class="text-title" v-html="addEmoji(String(item.username))"></div>
      </dd>
      <dd class="content" v-html="addEmoji(item.content)"></dd>
      <dd class="bottom">
        <span class="time">{{item.time | timeFormate}}</span>
        <a href="javascript:;" class="close" @click="wishDel(index,item.id)"></a>
      </dd>
    </dl>
  </div>
  <div class="send-form" :style="{display:sendFrame}">
    <p class="title"><span>发表你的记事</span><a href="javascript:;" id="close" @click="sendFrame='none'"></a></p>
    <form action="" name="wish">
      <div class="moa-item">
        <label class="label" for="username">标题：</label>
        <input type="text" @focus="ftype" name="username" id="username" v-model="username"/>
      </div>
      <div class="moa-item">
        <label class="label" for="content">内容：(您还可以输入&nbsp;<span id="font-num">{{maxTextLength - content.length}}</span>&nbsp;个字)</label>
        <textarea @focus="ftype" name="content" id="content" v-model="content"></textarea>
        <div id="phiz" class="mgt-05">
          <img class="emoji" v-for="(e, i) in emojiConf" :key="'l487'+i" :src="`static/Images/emoji/${e.emojiSrc}.png`" :alt="e.emojiDemo" @click="addOneEmoji(e.emojiDemo)" />
        </div>
      </div>
      <span id="send-btn" @click="send"></span>
    </form>
  </div>
  <!-- 注册窗口 -->
  <div class="send-form" v-show="isRegist === true">
    <p class="title"><span>注册：</span><a href="javascript:;" id="close" @click="isRegist = false"></a></p>
    <form class="form-content" action="" name="wish">
      <div class="moa-item">
        <label class="label" for="nickname">昵称：</label>
        <input type="text" name="nickname" v-model="regist.nickname"/>
      </div>
      <div class="moa-item">
        <label class="label" for="username">用户名：</label>
        <input type="text" name="username" v-model="regist.username"/>
      </div>
      <div class="moa-item">
        <label class="label" for="pass">密码：</label>
        <input type="password" name="pass" v-model="regist.pass"/>
      </div>
      <div class="moa-item">
        <label class="label" for="pass2">再次输入密码：</label>
        <input type="password" name="pass2" v-model="regist.pass2"/>
      </div>
      <p @click="writeMore = !writeMore">{{writeMore === false? '填写更多↓': '收起↑'}}（以下为非必填）</p>
      <div v-show="writeMore === true">
        <div class="moa-item">
          <label class="label" for="tel">电话号码</label>
          <input type="text" name="tel" v-model="regist.tel"/>
        </div>
        <div class="moa-item">
          <label class="label" for="email">邮箱</label>
          <input type="text" name="email" v-model="regist.email"/>
        </div>
        <div class="moa-item">
          <label class="label" for="address">联系地址</label>
          <input type="text" name="address" v-model="regist.address"/>
        </div>
        <div class="moa-item">
          <label class="label" for="sign">个人签名：(不可超过&nbsp;<span id="font-num">500</span>&nbsp;个字)</label>
          <textarea class="sign" name="sign" v-model="regist.sign"></textarea>
        </div>
      </div>
    </form>
    <div class="moa-item">
      <span class="moa-btn" @click="isLogin = true,isRegist = false">去登录</span>
      <span class="moa-btn flt-r" @click="fRegist">注册</span>
    </div>
  </div>
  <!-- 登录窗口 -->
  <div class="send-form" v-show="isLogin === true">
    <p class="title"><span>登录：</span><a href="javascript:;" id="close" @click="isLogin=false"></a></p>
    <form class="form-content" action="" name="wish">
      <div class="moa-item">
        <label class="label" for="username">用户名：</label>
        <input type="text" name="username" v-model="login.username"/>
      </div>
      <div class="moa-item">
        <label class="label" for="pass">密码：</label>
        <input type="password" name="pass" v-model="login.pass"/>
      </div>
    </form>
    <div class="moa-item">
      <span class="moa-btn" @click="isLogin = false,isRegist = true">去注册</span>
      <span class="moa-btn flt-r" @click="getToken">登录</span>
    </div>
  </div>
</div>
</template>
<script>
  import {STATUS_OK} from 'common/js/config'
  import md5 from 'common/js/md5'
  import axios from 'axios'
  // 获取光标位置
    function getSelection(el) {
      return (
      ('selectionStart' in el && function () {
          var l = el.selectionEnd - el.selectionStart;
          return {
              start: el.selectionStart,
              end: el.selectionEnd,
              length: l,
              text: el.value.substr(el.selectionStart, l)
          };
      }) ||

      (document.selection && function () {

          el.focus();

          var r = document.selection.createRange();
          if (r === null) {
              return {
                  start: 0,
                  end: el.value.length,
                  length: 0
              }
          }

          var re = el.createTextRange();
          var rc = re.duplicate();
          re.moveToBookmark(r.getBookmark());
          rc.setEndPoint('EndToStart', re);

          return {
              start: rc.text.length,
              end: rc.text.length + r.text.length,
              length: r.text.length,
              text: r.text
          };
      }) ||

      function () {
          return null;
      }

      )();

      }
      // 设置光标位置
      //设置光标位置函数 
      function setCursorPosition(ctrl, pos){
        if(ctrl.setSelectionRange){ 
          ctrl.focus(); 
          ctrl.setSelectionRange(pos,pos); 
        } else if (ctrl.createTextRange) { 
          var range = ctrl.createTextRange(); 
          range.collapse(true); 
          range.moveEnd('character', pos); 
          range.moveStart('character', pos); 
          range.select(); 
        } 
      }

      /**
       * 操作drag的函数
       */
      window.g_obj = {
        zIndex: 100
      }
      function handleDrag(el, isPc, vNode) {
        const jsId = el.getAttribute('jsId')
        let topH = document.querySelector('.top').offsetHeight;
        const vm = vNode.context
        if (isPc === true) {
          el.children[0].onmousedown = function(ev){
            // console.log(el)
            //  console.log(this);//事件对象
            //  el.style.zIndex=_this.zIndex++;  //_this 外面存的this(window)
              el.style.zIndex=vm.zIndex++;
            //  console.log(vm);
              var disX=ev.pageX - el.offsetLeft;
              var disY=ev.pageY - el.offsetTop;
              // 发送位置 1 --- 2019-1-5 15:39:13 ----------
              vm.recordPos.jsId = {
                id: jsId,
                timer: null,
                type: vm.selectSys
              }
              document.onmousemove=function(ev){
                let l=ev.pageX-disX;
                let t=ev.pageY-disY;//计算
                //限定
                if(l<0) l=0;
                if(t<0) t=0;
                if(l>document.documentElement.clientWidth-el.offsetWidth)
                  l=document.documentElement.clientWidth-el.offsetWidth;
                if(t>document.documentElement.clientHeight-el.offsetHeight- topH)
                  t=document.documentElement.clientHeight-el.offsetHeight-topH;
                el.style.left=l+'px';//使用
                el.style.top=t+'px';
                // 发送位置 2 新增 -- 记录下位置 ---- 2019-1-5 15:39:08----------
                // vm.recordPos.
                // console.log(el.getAttribute('jsId'))
                clearTimeout(vm.recordPos.jsId.timer)
                vm.recordPos.jsId.timer = null
                vm.recordPos.jsId['left'] =  l
                vm.recordPos.jsId['top'] =  t
              };
              document.onmouseup = function(){
                document.onmousemove=document.onmouseup=null;
                // 发送位置 3 --- 2019-1-5 15:39:13
                vm.recordPos.jsId.timer = setTimeout (()=>{
                  // 发送位置信息
                  let info = JSON.parse(JSON.stringify(vm.recordPos.jsId))
                  delete info.timer
                  vm.sendPos(info)
                },2000)
              };
              return false;
            };
        } else {
          el.children[0].ontouchstart = function(ev){
            // 发送位置 1 --- 2019-1-5 15:39:13 ----------
            vm.recordPos.jsId = {
              id: jsId,
              timer: null,
              type: vm.selectSys
            }
            // console.log(ev)
            //  console.log(this);//事件对象
            //  el.style.zIndex=_this.zIndex++;  //_this 外面存的this(window)
              el.style.zIndex=vm.zIndex++;
            //  console.log(vm);
              var disX=ev.targetTouches["0"].pageX - el.offsetLeft;
              var disY=ev.targetTouches["0"].pageY - el.offsetTop;
              document.ontouchmove=function(ev){
                let l=ev.targetTouches["0"].pageX-disX;
                let t=ev.targetTouches["0"].pageY-disY;//计算
                //限定
                if(l<0) l=0;
                if(t<0) t=0;
                if(l>document.documentElement.clientWidth-el.offsetWidth)
                  l=document.documentElement.clientWidth-el.offsetWidth;
                if(t>document.documentElement.clientHeight-el.offsetHeight-topH)
                  t=document.documentElement.clientHeight-el.offsetHeight-topH;
                el.style.left=l+'px';//使用
                el.style.top=t+'px';
                // 发送位置 2 新增 -- 记录下位置 ---- 2019-1-5 15:39:08----------
                // vm.recordPos.
                // console.log(el.getAttribute('jsId'))
                clearTimeout(vm.recordPos.jsId.timer)
                vm.recordPos.jsId.timer = null
                vm.recordPos.jsId['left'] =  l
                vm.recordPos.jsId['top'] =  t
              };
              document.ontouchend=function () {
                document.ontouchmove = document.ontouchend = null;
                // 发送位置 3 --- 2019-1-5 15:39:13
                vm.recordPos.jsId.timer = setTimeout (()=>{
                  // 发送位置信息
                  let info = JSON.parse(JSON.stringify(vm.recordPos.jsId))
                  delete info.timer
                  vm.sendPos(info)
                },2000)
              };
              return false;
            };
        }
      }

  export default {
    name: 'overview',
    components: {},
    data() {
      return {
        titleMaxLength: 80,
        // 内容最大长度设置限制
        maxTextLength: 500,
        // 配置广场位置，部署不同平台将在不同位置
        dbTable: 'wish',
        // api: 'http://172.25.49.124:8002',
        api: 'http://www.7moa.com:8002',
        username:'',
        content:'',
        sendFrame:'none',
        arr:[],
        zIndex:100,
        login: {
          nickname: '',
          username: '',
          pass: '',
          tel: '',
          email: '',
          address: '',
          sign: '',
        },
        regist: {
          nickname: '',
          username: '',
          pass: '',
          tel: '',
          email: '',
          address: '',
          sign: '',
        },
        isPc: 0,
        isLogin: false,
        isRegist:false,
        sToken: this.getCookie('sToken'),
        sUsername: this.getCookie('username'),
        // 默认0，在广场上
        selectSys: 0,
        writeMore: false,
        //表情配置
        emojiConf: [
          {emojiSrc:"ee_1",emojiDemo:"[):]"},
          {emojiSrc:"ee_2",emojiDemo:"[:D]"},
          {emojiSrc:"ee_3",emojiDemo:"[;)]"},
          {emojiSrc:"ee_4",emojiDemo:"[:-o]"},
          {emojiSrc:"ee_5",emojiDemo:"[:p]"},
          {emojiSrc:"ee_6",emojiDemo:"[(H)]"},
          {emojiSrc:"ee_7",emojiDemo:"[:@]"},
          {emojiSrc:"ee_8",emojiDemo:"[:s]"},
          {emojiSrc:"ee_9",emojiDemo:"[:$]"},
          {emojiSrc:"ee_10",emojiDemo:"[:(]"},
          {emojiSrc:"ee_11",emojiDemo:"[:'(]"},
          {emojiSrc:"ee_12",emojiDemo:"[:|]"},
          {emojiSrc:"ee_13",emojiDemo:"[(a)]"},
          {emojiSrc:"ee_14",emojiDemo:"[8o|]"},
          {emojiSrc:"ee_15",emojiDemo:"[8-|]"},
          {emojiSrc:"ee_16",emojiDemo:"[+o(]"},
          {emojiSrc:"ee_17",emojiDemo:"[<o)]"},
          {emojiSrc:"ee_18",emojiDemo:"[|-)]"},
          {emojiSrc:"ee_19",emojiDemo:"[*-)]"},
          {emojiSrc:"ee_20",emojiDemo:"[:-#]"},
          {emojiSrc:"ee_21",emojiDemo:"[:-*]"},
          {emojiSrc:"ee_22",emojiDemo:"[^o)]"},
          {emojiSrc:"ee_23",emojiDemo:"[8-)]"},
          {emojiSrc:"ee_24",emojiDemo:"[(|)]"},
          {emojiSrc:"ee_25",emojiDemo:"[(u)]"},
          {emojiSrc:"ee_26",emojiDemo:"[(S)]"},
          {emojiSrc:"ee_27",emojiDemo:"[(*)]"},
          {emojiSrc:"ee_28",emojiDemo:"[(#)]"},
          {emojiSrc:"ee_29",emojiDemo:"[(R)]"},
          {emojiSrc:"ee_30",emojiDemo:"[({)]"},
          {emojiSrc:"ee_31",emojiDemo:"[(})]"},
          {emojiSrc:"ee_32",emojiDemo:"[(k)]"},
          {emojiSrc:"ee_33",emojiDemo:"[(F)]"},
          {emojiSrc:"ee_34",emojiDemo:"[(W)]"},
          {emojiSrc:"ee_35",emojiDemo:"[(D)]"}
        ],
        focusTarget: '',
        // 记录个人中心每个便签的位置
        recordPos: {},
        searchText: '',
      }
    },
    methods:{
      formatDate(ms, format){
        var currentdate,
          date=new Date(ms),
          cut1="-",
          cut2=":",
          objYear=date.getFullYear(),
          objMonth=date.getMonth()+1,
          objDate=date.getDate(),
          objHours=date.getHours(),
          objMinutes=date.getMinutes(),
          objSeconds=date.getSeconds()
        if(objMonth>=1 && objMonth<=9){
            objMonth="0"+objMonth;
        }
        if(objDate>=0 && objDate<=9){
            objDate="0"+objDate;
        }
        if(objHours>=0 && objHours<=9){
            objHours="0"+objHours;
        }
        if(objMinutes>=0 && objMinutes<=9){
            objMinutes="0"+objMinutes;
        }
        if(objSeconds>=0 && objSeconds<=9){
            objSeconds="0"+objSeconds;
        }
        if (typeof format !== 'number' || format === 3) {
          // 默认值
          currentdate=objYear+cut1+objMonth+cut1+objDate
        }
        else if(format==2){
          currentdate=objYear+cut1+objMonth
        }
        else if(format==5){
          currentdate=objYear+cut1+objMonth+cut1+objDate+" "+objHours+cut2+objMinutes
        }
        else if(format==6){
          currentdate=objYear+cut1+objMonth+cut1+objDate+" "+objHours+cut2+objMinutes+cut2+objSeconds
        }
        else{
          currentdate=objYear+cut1+objMonth+cut1+objDate+" "+objHours+cut2+objMinutes
        }
        return currentdate;
      },
      filterData(arr){
        // this.searchText
        if (typeof arr !== 'object') {
          return arr
        } else {
          return arr.filter((e)=>{
            let str = ''
            if ('userName' in e) {
              str = String(e.userName) + e.content + this.formatDate(e.time, 5)
            } else {
              str = String(e.username) + e.content + this.formatDate(e.time, 5)
            }
            return str.indexOf(this.searchText) !== -1
          })
        }
      },
      sendPos(p){
        // id: jsId,
        // type: vm.selectSys,
        // left: l,
        // top: t 
        // device： 0 为 移动， 1为pc 
        p.isPc = Number(this.isPc)
        p.table = this.dbTable
        axios({
          method: 'post',
          // url:'./wish.php',
          url: this.api + '/wish/recordPos',
          data: p
        }).then((res)=>{
          // console.log('line 305')
        //  {error:1, msg:xxx, id: 心愿ID, time: 1435567718}
          if(res.status === 200 && res.data.status === 2000){
            //数据操作 {error:0, id: 新添加内容的ID, time: 添加时间}
            // console.log(res.data)
          }
        })
      },
      ftype(ev){
        this.focusTarget = ev.target.id
      },
      getCookie(e){
        let arr = document.cookie.split('; ')
        const len = arr.length
        let target = []
        for(let i = 0; i< len; i++){
          if (arr[i].indexOf(e) !== -1 ) {
            target = arr[i].split('=')
            break
          }
        }
        if (target.length > 1) {
          return target[1]
        } else if (target.length === 1) {
          return target[0]
        } else {
          return ''
        }
      },
      //发布愿望
      send(){
        if (this.content.trim() === '') {
          alert('内容不能为空白哦~')
          return;
        }
        this.sendFrame='none';
        //发表许愿wish.php?act=add&username=xxx&content=xxx
        let params = {
          id: this.randomString(8),
          username:this.username,
          content:this.content,
          time: + new Date(),
          isPc: Number(this.isPc),
          table:  this.dbTable
        }
        if (this.selectSys === 1 && this.sToken !== '') {
          params.sToken = this.sToken
          params.sUsername = this.sUsername
        }
        axios({
          method: 'post',
          // url:'./wish.php',
          url: this.api + '/wish/create',
          data: params
        }).then((res)=>{
        //  {error:1, msg:xxx, id: 心愿ID, time: 1435567718}
          if(res.status === 200 && res.data.status === 2000){
            //数据操作 {error:0, id: 新添加内容的ID, time: 添加时间}
            let num = this.arr.length + 1;
            if(this.arr.length > 0){
              num = this.arr[this.arr.length - 1].num + 1
            } else {
              num = 1
            }
            this.arr.push({
              id: params.id,
              num: num,
              username: params.username,
              content: params.content,
              time: params.time,
            });
            this.username=this.content='';
          }
          if (res.data.status === 4003){
            // 后面增加页面提示，like rap的页面提示，非弹窗，可以让他一直在
            document.cookie=`sToken=''; expires=${new Date((+ new Date()) - 24*60*60000).toGMTString()}`
            alert('token已过期，请重新登录！')
              if(this.selectSys === 1){
                this.selectSys = 0
              }
            this.sToken = ''
          }
        })
      },
      //获取所有愿望
      getWish(){
        let params = {
          isPc: Number(this.isPc),
          table:  this.dbTable
        }
        if (this.selectSys === 1 && this.sToken !== '') {
          params.sToken = this.sToken
          params.sUsername = this.sUsername
        }
        //wish.php?act=get
        this.arr = []
        axios({
          method: 'post',
          // url:'./wish.php',
          url: this.api + '/wish/list',
          data: params
        }).then((res)=>{
        //  {error:0, msg:[{'id':1, 'username':'xxx', 'content':'xxx', time: 1435567718},{},{},{}.......]}
          if (res.status === 200 && res.data.status === 2000) {
            //数据操作 {error:0, id: 新添加内容的ID, time: 添加时间}
            this.arr=res.data.content;
          }
          if (res.data.status === 4003){
            // 后面增加页面提示，like rap的页面提示，非弹窗，可以让他一直在
            document.cookie=`sToken=''; expires=${new Date((+ new Date()) - 24*60*60000).toGMTString()}`
            alert('token已过期，请重新登录！')
              if(this.selectSys === 1){
                this.selectSys = 0
              }
            this.sToken = ''
          }
        })
      },
      //删除一条愿望
      wishDel (index,id) {
        if(this.sUsername === ''){
          alert('您未登录！(找不到用户名)')
          return
        }
        if(this.sToken === '') {
          alert('您未登录！（无token）')
          return
        } else {
          if(this.selectSys === 0) {
            if (this.sUsername !== 'dongchen') {
              alert('只有管理员能对广场上的便签操作')
              return
            }
          }
          let params = {
            username: this.sUsername,
            sToken: this.sToken,
            id: id,
            type: this.selectSys,
            isPc: Number(this.isPc),
            table: this.dbTable
          }
          axios({
            method: 'post',
            url: this.api + '/wish/del',
            data: params
          }).then((res)=>{
            if(res.data.status === 2000){
              // 删除成功
              this.arr.splice(index,1);
            }
            if (res.data.status === 4003){
              // 后面增加页面提示，like rap的页面提示，非弹窗，可以让他一直在
              document.cookie=`sToken=''; expires=${new Date((+ new Date()) - 24*60*60000).toGMTString()}`
              alert('token已过期，请重新登录！')
              if(this.selectSys === 1){
                this.selectSys = 0
              }
              this.sToken = ''
            }
          },(res)=>{
            console.log(res);
          })
        }
      },
      randomString: function(len) {
        len = len || 32
        var $chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678'
        var maxPos = $chars.length
        var pwd = ''
        for (let i = 0; i < len; i++) {
          if(i < 1){
            pwd += $chars.charAt(Math.floor(Math.random() * (maxPos - 7)))
          } else {
            pwd += $chars.charAt(Math.floor(Math.random() * maxPos))
          }
        }
        return pwd
      },
      getToken(){
        if (this.login.username.trim() === '') {
          alert('用户名不能为空')
          return
        }
        if (this.login.pass.trim() === '') {
          alert('密码不能为空')
          return
        }
        let params = {
          username: this.login.username,
          isPc: Number(this.isPc)
        }
        axios({
          method: 'post',
          // url:'./wish.php',
          url: this.api + '/moa/getToken',
          data: params
        }).then((res)=>{
          if(res.status === 200 && res.data.status === 2000){
            // console.log(res.data)
            if(res.data.content === ''){
              alert('需要先注册哦~')
              return
            }
            this.fLogin(res.data.content)
          }
        })
      },
      fLogin(token){
        const passwd = md5(md5(this.login.pass) + 'moa' + token)
        const sUsername = this.login.username
        let params = {
          username: this.login.username,
          pass: passwd,
          isPc: Number(this.isPc)
        }
        axios({
          method: 'post',
          // url:'./wish.php',
          url: this.api + '/moa/login',
          data: params
        }).then((res)=>{
          if(res.status === 200 && res.data.status === 2000){
            // console.log(res)
            // 登录成功
            // passwd存cookie
            // document.cookie="userId=828; userName=hulk; expire="+date.toGMTString(); 
            const timeStamp = + new Date
            // console.log((new Date(timeStamp + 24*60*60000)).toGMTString())
            // 设置一天过期
            document.cookie=`username=${sUsername}; expires=${(new Date(timeStamp + 24*60*60000)).toGMTString()}`
            document.cookie=`sToken=${passwd}; expires=${(new Date(timeStamp + 24*60*60000)).toGMTString()}`
            this.sToken = passwd
            this.sUsername = sUsername
            this.login.pass = ''
            this.login.username = ''
            // 切换到个人记事
            this.arr = []
            if(this.selectSys === 0) {
              this.selectSys = 1
            } else {
              this.getWish()
            }
            this.isLogin = false;
          }
          alert(res.data.msg)
        })
      },
      fRegist(){
        let params = JSON.parse(JSON.stringify(this.regist))
        if (params.username.trim() === '') {
          alert('用户名不能为空')
          return
        }
        if (params.pass.trim() === '') {
          alert('密码不能为空')
          return
        }
        params.pass = md5(this.regist.pass)
        axios({
          method: 'post',
          // url:'./wish.php',
          url: this.api + '/moa/register',
          data: params
        }).then((res)=>{
          if(res.status === 200 && res.data.status === 2000){
            // console.log(res)
            this.login.username = this.regist.username
            this.login.pass = this.regist.pass
            for(k in this.regist) {
              this.regist[k] = ''
            }
            // 前往登录
            this.isRegist = false
            this.isLogin = true
          }
          alert(res.data.msg)
        })
      },
      // 对表情文字进行替换为 图片
      addEmoji(item){
        var html = "";
        //新增--解析表情
        //var newCom = item.content.replace(/(\[.*\])/g, (match) => {
        var newCom = item.replace(/\[[^\[\]$]*\]/g, (match) => {
            var replaceStr = '';
            //console.log(match);
            for (var imgItem of this.emojiConf) {
                if (match === imgItem.emojiDemo) {
                  //console.log("match")
                  //replaceStr = `<img width="28" height="28" src="./img/${imgItem.emojiSrc}.png" />`;
                  //item.content.replace('[:D]',replaceStr);
                  //console.log(item.content)
                  //alert("匹配上")
                    replaceStr += "<img src='static/Images/emoji/"+imgItem.emojiSrc+".png' />";
                }
            }
              return replaceStr === '' ? match : replaceStr
          });
          return newCom
      },
      // 增加一个表情
      addOneEmoji(demo){
        let el = document.querySelector('#content')
        if(this.focusTarget !== '') {
          el = document.getElementById(this.focusTarget)
        }
        // console.log(el)
        const pos = getSelection(el)
        if(this.focusTarget === 'username') {
          this.username = this.username.slice(0, pos.start) + demo + this.username.slice(pos.end)
        } else {
          this.content = this.content.slice(0, pos.start) + demo + this.content.slice(pos.end)
        }
        // 重设光标位置
        // console.log(pos.start)
        this.$nextTick(()=>{
          setCursorPosition(el, pos.start + demo.length)
        })
      }
    },
    mounted(){
      let el = document.getElementById('app')
      // console.log('ontouchstart' in el)
      // 判断是否是pc设备
      this.isPc = !('ontouchstart' in el);
      if(this.isPc === false){
        document.getElementById('app').className = document.getElementById('app').className + ' h5'
        document.getElementsByTagName('html')[0].setAttribute('style', 'font-size: 15px')
      }
      this.getWish();
      // const el = document.querySelector('#content')
      // console.log(getSelection(el))
    },
    created(){
      
    },
    watch: {
      selectSys(){
        this.searchText = ''
        let el = document.getElementById('app')
        // console.log('ontouchstart' in el)
        this.isPc = !('ontouchstart' in el);
        this.getWish()
      },
      content(e){
        if(e.length > this.maxTextLength){
          this.content = String(this.content).slice(0, this.maxTextLength)
          setCursorPosition(document.getElementById('content'), this.maxTextLength)
        }
      },
      // 标签的标题 长度限制
      username(e){
        if(e.length > this.titleMaxLength){
          this.username = String(this.username).slice(0, this.titleMaxLength)
          alert('标题的最大字数为'+ this.titleMaxLength)
          setCursorPosition(document.getElementById('username'), this.titleMaxLength)
        }
      }
    },
    directives: {
      drag: {
        inserted: (el, binding, vNode) => { //插入到dom时候在执行
          // binding 是接收值的
          // binding.value
          // console.log(binding.value)
          //  var _this=this; //window
          // console.log(vm)
          console.log(vNode.context.selectSys)
          let ell = document.getElementById('app')
          // console.log('ontouchstart' in el)
          let isPc = !('ontouchstart' in el);
          let rnd = (n, m) => {
              return parseInt(n + Math.random() * (m - n))
          };
          //随机位置、颜色、限定
          el.style.left = rnd(0, document.documentElement.clientWidth - el.offsetWidth) + 'px';
          el.style.top = rnd(0, document.documentElement.clientHeight - el.offsetHeight - 126) + 'px';
          // 恢复pc 或者其他设备 的 位置 -- 新增 -- 2019-1-5 16:04:27
          if (isPc === true) {
              if (typeof binding.value.left === 'number') {
                  el.style.left = binding.value.left + 'px'
              }
              if (typeof binding.value.top === 'number') {
                  el.style.top = binding.value.top + 'px'
              }
          } else {
              if (typeof binding.value.left2 === 'number') {
                  el.style.left = binding.value.left2 + 'px'
              }
              if (typeof binding.value.top2 === 'number') {
                  el.style.top = binding.value.top2 + 'px'
              }
          }
          el.className = 'paper a' + rnd(1, 6);
          handleDrag(el, isPc, vNode)
        }
      }
    }
  }
</script>
<style scoped>
  .main {
    margin: 20px auto 0px auto;
  }
  .hive-over-text{
    text-overflow: ellipsis;
  }

  .panel {
    width: 97%;
    margin-bottom: 20px;
    background-color: #fff;
    border: 1px solid transparent;
    border-radius: 4px;
    margin-top: 30px;
    box-shadow: 0 1px 1px rgba(0, 0, 0, .05);
  }

</style>
